//
//  NDHomeViewModel.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/10/8.
//

import Foundation

class NDHomeViewModel: ObservableObject {
    @Published var homeListData: HomeDataModel?
    @Published var isLoading = false
    @Published var errorMessage: String?
    
    // 处理后的数据
    @Published var largeCardModel: PachistItem?
    @Published var smallCardModel: PachistItem?
    @Published var productListModel: PachistItem?
    @Published var repaymentModel: PachistItem?
    @Published var productCard: ProductCard?
    @Published var currentPetitor: Petitor?
    
    func loadHomeData() {
        isLoading = true
        errorMessage = nil
        
        NDRequestManager.requestHomeData { [weak self] homeListData, msg, error in
            guard let self = self else { return }
            DispatchQueue.main.async {
                self.isLoading = false
                
                if let error = error {
                    self.errorMessage = msg
                    print("请求失败: \(error)")
                    return
                }
                
                guard let homeListData = homeListData else {
                    self.errorMessage = "no data"
                    return
                }
                
                self.homeListData = homeListData
                self.processHomeData(homeListData)
            }
        }
    }
    
    private func processHomeData(_ homeListData: HomeDataModel) {
        guard let septenier = homeListData.pachist else { return }
        
        // 分离数据处理逻辑
        processCardModels(septenier)
        processProductList(septenier)
        processRepaymentData(septenier)
    }
    
    private func processCardModels(_ septenier: [PachistItem]) {
        // 大卡位数据
        largeCardModel = septenier.first { $0.olig == "quatiturnade" }
        
        // 小卡位数据
        smallCardModel = septenier.first { $0.olig == "quiteoon" }
        
        // 设置顶部接收器
        if let corditModel = largeCardModel ?? smallCardModel {
            productCard = corditModel.productCard
            NDUserDefaults.shared.saveText(productCard?.fascletterism ?? "", for: NDAppNameKey)
        }
    }
    
    private func processProductList(_ septenier: [PachistItem]) {
        productListModel = septenier.first { $0.olig == "cristhealthan" }
    }
    
    private func processRepaymentData(_ septenier: [PachistItem]) {
        repaymentModel = septenier.first { $0.olig == "cand" }
    }
    
//    // 获取图片 URL
//    func getImageURL() -> String? {
//        guard let baseURL = productCard?.juxtaette else { return nil }
//        let queryString = NetworkManager.shared.commonParameters.urlQueryString
//        return "\(baseURL)?\(queryString)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
//    }
}
